using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Diagnostics.Contracts;

namespace IWMAG.Core.Helpers {
    public class GameConsole {
        public GameConsole()
        {
            this._writer = GetDefaultWriter();
            ResetText();
        }

        public void ResetText()
        {
            this.Text = "";
        }

        public TextWriter GetDefaultWriter()
        {
            return new GameConsoleWriter(this);
        }
        public string Text { get; protected set; }

        private TextWriter _writer;
        public TextWriter Writer {
            get {
                return _writer;
            }
        }

        public void Update(float duration) {
            //Reader.BaseStream.Seek(0, SeekOrigin.Begin);
           
                string[] lines = Text.Split('\n');
                if (lines.Length > 10) {
                    Text = "";
                    for (int i = 0; i < 10; i++) {
                        Text += lines[i + lines.Length - 10 - 1] + "\n";
                    }
                
                
                //Text = Reader.ReadToEnd();
            }
        }

        private class GameConsoleWriter : TextWriter
        {
            private GameConsole console;
            public GameConsoleWriter(GameConsole c)
            {
                this.console = c;
            }

            private void WriteImpl(string s)
            {
                console.Text += s;
            }

            public override void Write(string value)
            {
                Contract.Requires(value != null);
                WriteImpl(value);
            }

            public override void WriteLine(string value)
            {
                Contract.Requires(value != null);
                WriteImpl(value + Environment.NewLine);
            }

            public override void Write(char value)
            {
                WriteImpl(value.ToString());
            }

            public override Encoding Encoding
            {
                get { return System.Text.Encoding.Default; }
            }
        }
    }
}
